/*
 * Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & www.dreamlu.net).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.dreamlu.system.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import net.dreamlu.common.utils.FreemarkerUtil;
import net.dreamlu.db.manager.AdminManager;
import net.dreamlu.db.manager.AdminRoleManager;
import net.dreamlu.db.manager.OrganizationManager;
import net.dreamlu.db.po.Admin;
import net.dreamlu.db.po.AdminRole;
import net.dreamlu.db.po.Organization;
import net.dreamlu.db.po.Role;
import net.dreamlu.db.qo.AdminQuery;
import net.dreamlu.db.qo.AdminRoleQuery;
import net.dreamlu.mica.core.utils.BeanUtil;
import net.dreamlu.system.service.IAdminService;
import net.dreamlu.system.vo.AdminVO;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author L.cm
 * @since 2018-01-29
 */
@Service
public class AdminServiceImpl implements IAdminService {
	@Autowired
	private OrganizationManager	organizationMapper;
	@Autowired
	private AdminRoleManager	adminRoleMapper;
	@Autowired
	private AdminManager		adminManager;
	@Autowired
	private JdbcTemplate		jdbcTemplate;

	@PersistenceContext
	private EntityManager		entityManager;
	

	@Override
	public Admin findByName(String username) {
		Admin admin = new Admin();
		admin.setUsername(username);
		AdminQuery query = new AdminQuery();
		query.setUsername(username);
		return adminManager.queryUniqueAdmin(query);
	}

	@Override
	public Page<AdminVO> finalDataGrid(AdminVO adminVO, Pageable pageable) {
		LocalDateTime startTime = adminVO.getCreatedateStart();
		LocalDateTime endTime = adminVO.getCreatedateEnd();
		AdminQuery adminQuery = new AdminQuery();
		adminQuery.setCreateTimeBegin(startTime);
		adminQuery.setCreateTimeEnd(endTime);
		adminQuery.setOrganizationId(adminVO.getOrganizationId());
		Page<Admin> page = adminManager.queryAdminByPage(pageable, adminQuery);
		List<AdminVO> adminVOList = new ArrayList<>();
		for (Admin _admin : page.getContent()) {
			AdminVO _adminVO = BeanUtil.copy(_admin, AdminVO.class);
			// 处理组织名
			Organization organization = organizationMapper.queryOrganizationById(_admin.getOrganizationId());
			_adminVO.setOrganizationName(organization.getName());
			String sql = FreemarkerUtil.sql2String(null, "findListByAdminId.sql");
			RowMapper<Role> rm = BeanPropertyRowMapper.newInstance(Role.class);
			List<String> roleNameList = jdbcTemplate.query(sql, new Object[] { _admin.getId() }, rm).stream().map(Role::getName).collect(Collectors.toList());
			// 处理角色集合
			_adminVO.setRolesList(roleNameList);
			adminVOList.add(_adminVO);
		}
		Page<AdminVO> adminVOPage = new PageImpl<>(adminVOList, pageable, page.getSize());
		return adminVOPage;
	}

	@Override
	public boolean insertByVo(AdminVO adminVO) {
		Admin admin = BeanUtil.copy(adminVO, Admin.class);
		adminManager.saveAdmin(admin);

		Integer id = admin.getId();
		String[] roles = adminVO.getRoleIds().split(",");
		AdminRole adminRole = new AdminRole();
		for (String string : roles) {
			adminRole.setAdminId(id);
			adminRole.setRoleId(Integer.valueOf(string));
			adminRoleMapper.saveAdminRole(adminRole);
		}
		return true;
	}

	@Override
	public boolean updateByVo(AdminVO adminVO) {
		Admin admin = adminManager.queryAdminById(adminVO.getId());
		BeanUtil.copyNonNull(adminVO, admin);
		adminManager.saveAdmin(admin);
		Integer id = adminVO.getId();

		AdminRoleQuery query = new AdminRoleQuery();
		query.setAdminId(id);
		List<AdminRole> adminRoles = adminRoleMapper.queryAdminRole(query);
		if (adminRoles != null && !adminRoles.isEmpty()) {
			for (AdminRole adminRole : adminRoles) {
				adminRoleMapper.deleteAdminRoleByIds(adminRole.getId());
			}
		}
		String[] roles = adminVO.getRoleIds().split(",");
		AdminRole adminRole = new AdminRole();
		for (String string : roles) {
			adminRole.setAdminId(id);
			adminRole.setRoleId(Integer.valueOf(string));
			adminRoleMapper.saveAdminRole(adminRole);
		}
		return true;
	}
}
